package com.xbongbong.paas.elasticsearch.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.pro.constant.BusinessConstant;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2020/10/15 16:32
 */
public class FormSubDataUtil {

    public static void setSubData(List<? extends PaasFormDataEntity> list, List<PaasFormSubDataEntity> subDataList) {
        if (CollectionsUtil.isEmpty(list) || CollectionsUtil.isEmpty(subDataList)) {
            return;
        }
        Map<Long, Map<String, JSONArray>> subMap = getSubMap(subDataList);
        list.forEach(item -> {
            Map<String, JSONArray> subData = subMap.get(item.getId());
            if (Objects.nonNull(subData)) {
                setSubData(item, subData);
            }
        });
    }


    public static void setSubDataBySingle(PaasFormDataEntityExt paasFormDataEntity, List<PaasFormSubDataEntity> subDataList) {
        if (Objects.isNull(paasFormDataEntity) || CollectionsUtil.isEmpty(subDataList)) {
            return;
        }
        Map<Long, Map<String, JSONArray>> subMap = getSubMap(subDataList);

        Map<String, JSONArray> subData = subMap.get(paasFormDataEntity.getId());
        if (Objects.nonNull(subData)) {
            setSubData(paasFormDataEntity, subData);
        }
    }

    private static void setSubData(PaasFormDataEntity paasFormDataEntity,  Map<String, JSONArray> subData ) {
        subData.forEach((k, v) -> {
            if (Objects.nonNull(paasFormDataEntity.getData())) {
                paasFormDataEntity.getData().put(k, v);
            } else {
                JSONObject data = new JSONObject();
                data.put(k, v);
                paasFormDataEntity.setData(data);
            }
        });
    }

    private static Map<Long, Map<String, JSONArray>> getSubMap(List<PaasFormSubDataEntity> subDataList) {
        Map<Long, Map<String, JSONArray>> subMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormSubDataEntity subDataEntity : subDataList) {
            JSONObject data = subDataEntity.getData();
            if (Objects.isNull(data)) {
                data = new JSONObject();
            }
            data.put(BusinessConstant.SUB_DATA_ID, subDataEntity.getId());
            subDataEntity.setData(data);
            subMap.computeIfAbsent(subDataEntity.getDataId(), v -> new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY)).computeIfAbsent(subDataEntity.getAttr(), v -> new JSONArray()).add(data);
        }
        return subMap;
    }
}
